import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
const debug = process.env.NODE_ENV !== "production";

import cookie from "@/utils/store/cookie";
import {
	getUserInfo,
	getUser
} from "@/api/user";
import dialog from "@/utils/dialog";
import {
	createSocket
} from "@/api/public.js";
const loginKey = "login_status";
const IS_PRO = true;
const vuexStore = new Vuex.Store({
	state: {

		lastDeviceId: "",
		//屏幕宽度
		windowWidth: 0,
		//设备是否绑定
		deviceConect: false,
		//设备状态 0空闲  1运行中 2设备异常 3设备离线中
		deviceStauts: 3,
		//设备信息
		deviceInfo: {
			merchantName: "",
			deviceName: "",
			deviceId: ""
		},
		// 是否已经在授权页面
		isAuthorizationPage: false,
		// 是否授权
		isAuthorization: false,
		// 不建议从这里取 token，但是删除掉会影响其他的页面
		token: cookie.get(loginKey) || null,
		userInfo: cookie.get('userInfo'),
		$deviceType: null,
		location: {
			latitude: '',
			longitude: ''
		},
		storeItems: cookie.get("storeItems") || null,
		goName: cookie.get("goName") || "",
		socket: undefined,
		$is_open_socket: false,
		statusBarHeight: 0,
		counter: {
			baseUrl: IS_PRO ? "https://api.chzjzs.top/" : "https://api.zbqjc.com/",
			// user_id: uni.getStorageSync('user_id'),
			// shop_id: uni.getStorageSync('shop_id'),
			adult: uni.getStorageSync('isAdult'), // 是否成年 0 T 1F
			user_money: 0, // 用户余额
			access_token: uni.getStorageSync('access_token'), // 令牌
			refresh_token: uni.getStorageSync('refresh_token'), // 长期令牌用来刷新
			user_imgs: null,
			hasLogin: false, // 是否登录
			sfz_id: 0,
			sfz_name: null,
			UserConfig: [], // 用户更多参数
			Betrecord: [], // 我的 投注记录
			onHide_boole: false, // 是否后台进入（启动app不会触发全局onHide方法，用于用户长期挂在后台token过期后用户进入无法跳转值登录的问题）
			submitData: [], // 数字类彩票'不用了'
			submitNewData: [], // 数字类彩票投注单
			userinfo: [],
			matchInfoList: [], // 竞彩足球
			BettingContent:{Content:[],valuesdata:{}}, // 投注内容
			styleData: {
				data: []
			}, // 体彩样式变更
			valuesdata:{},
			allOrderData: [],
			userAllData: [], // 用户所有的信息
			gameAstrict: [], // 首页玩法用户点击限制
			allGameAstrict: [], // 首页所有玩法限制
			skipDetails: [], // 跟单/合买大厅跳转详情
			shop_info: [], // 用户上级店铺信息
			user_chatList: [], // 聊天室聊天记录
			chatPageExecute_user: '' // 聊天页面数据执行（用于监听后同步数据）
		}

	},
	mutations: {
		setStatusBarHeight(state, statusBarHeight) {
			state.statusBarHeight = statusBarHeight;
		},
		setwindowWidth(state, windowWidth) {
			state.windowWidth = windowWidth;
		},
		setDeviceConect(state, deviceId) {
			state.deviceInfo.deviceId = deviceId;
			state.deviceConect = true;
		},
		setLastDeviceId(state, id) {
			state.lastDeviceId = id;
		},
		setDeviceInfo(state, status) {
			state.deviceStauts = status;
			state.deviceConect = true;
			console.log(state.deviceInfo, status)
		},
		setDeviceMerName(state, info) {
			state.deviceConect = true;
			state.deviceInfo.merchantName = info.merName
			state.deviceInfo.name = info.name
			state.deviceInfo.deviceId = info.code
		},
		changeis_open_socket(state) {
			state.$is_open_socket = !state.$is_open_socket
		},
		changeis_open_socketfalse(state) {
			state.$is_open_socket = false
		},
		addSocket(state, soc) {
			state.socket = soc
		},
		login(state, token, expires_time) {
			state.token = token;
			cookie.set(loginKey, token, expires_time);
		},
		logout(state) {
			console.log('清除数据')
			state.token = null;
			state.userInfo = null
			cookie.clearAll()
		},
		backgroundColor(state, color) {
			state.color = color;
			// document.body.style.backgroundColor = color;
		},
		updateUserInfo(state, userInfo) {
			state.userInfo = userInfo;
			if (userInfo) {
				cookie.set('userInfo', userInfo)
			} else {
				cookie.set('userInfo', null)
			}
		},
		updateAuthorizationPage(state, isAuthorizationPage) {
			state.isAuthorizationPage = isAuthorizationPage;
		},
		updateAuthorization(state, isAuthorization) {
			state.isAuthorization = isAuthorization;
		},
		updateDevicetype(state, $deviceType) {
			state.$deviceType = $deviceType;
		},
		setLocation(state, location) {
			state.location = location
		},
		get_store(state, storeItems) {
			state.storeItems = storeItems;
			cookie.set("storeItems", storeItems);
		},
		get_to(state, goName) {
			state.goName = goName;
			cookie.set("goName", goName);
		},
		setBettingContent(state, BettingContent) {
			state.counter.BettingContent = BettingContent
		},
		setValuesdata(state, valuesdata) {
			state.counter.BettingContent.valuesdata = valuesdata
		},
		UPDATE_BETTING_CONTENT(state, payload) {
			const sortedContent = payload.BettingContent.Content.sort((a, b) => a.matchId - b.matchId);
			state.counter.BettingContent = {
				...payload.BettingContent,
				Content: sortedContent
			};
		},
		ADD_GAME_DATA_TO_CONTENT(state, payload) {
			state.counter.BettingContent.Content.push(payload.gameData);
		},
		UPDATE_GAME_DATA_IN_CONTENT(state, payload) {
			const index = state.counter.BettingContent.Content.findIndex(item => item.matchId === payload.matchId);
			if (index !== -1) {
				state.counter.BettingContent.Content[index] = payload.gameData;
			}
		},
		REMOVE_GAME_DATA_FROM_CONTENT(state, payload) {
			const index = state.counter.BettingContent.Content.findIndex(item => item.matchId === payload.matchId);
			if (index !== -1) {
				state.counter.BettingContent.Content.splice(index, 1);
			}
		},
		UPDATE_COUNT_AND_SELECT_NUMBER(state, payload) {
			// 根据实际情况来决定是增加还是减少count和selectNumber
			if (payload.isAdd) {
				state.counter.count++;
				state.counter.tabsArr[state.showData_index].selectNumber++;
			} else {
				state.counter.count--;
				state.counter.tabsArr[state.showData_index].selectNumber--;
			}
		}

	},
	actions: {
		updatevaluesdata({ commit }, data){
			  commit('setValuesdata', data);
		},
		updateSharedData({ commit }, data) {
		      commit('setBettingContent', data);
		    },
		setWindowWidth({
			state,
			commit
		}) {
			const {
				windowWidth,
				windowHeight
			} = uni.getSystemInfoSync();
			commit("setwindowWidth", windowWidth)
			console.log("commit( windowWidth)", windowWidth)
		},
		getLocation({
			state,
			commit
		}, force) {
			uni.getLocation({
				type: 'gcj02',
				success: function(res) {
					console.log(res)
					commit("setLocation", {
						longitude: res.longitude,
						latitude: res.latitude,
					});
				}
			});
		},
		userInfo({
			state,
			commit
		}, force) {
			if (state.userInfo !== null && !force) {
				return Promise.resolve(state.userInfo);
			}
			return new Promise(reslove => {
				getUserInfo().then(res => {
					commit("updateUserInfo", res.data);
					reslove(res.data);
				});
			}).catch(() => {
				uni.showToast({
					title: "获取信息失败!",
					icon: "none",
					duration: 2000,
				});
			});
		},
		getUser({
			state,
			commit
		}) {
			if (!state.token) {
				return Promise.reject('未获取到token');
			}
			return new Promise(reslove => {
				getUserInfo().then(res => {
					console.log(res)
					commit("updateUserInfo", res.data);
					reslove(res.data);
				});
			}).catch((error) => {
				console.log(error)
				uni.showToast({
					title: "获取信息失败!",
					icon: "none",
					duration: 2000,
				});
			});
		},
		changeLogin({
			state,
			commit
		}, data, date) {
			commit("login", data, date);
		},
		setUserInfo({
			state,
			commit
		}, user) {

			commit("updateUserInfo", user);
		},
		changeAuthorizationPage({
			state,
			commit
		}, index) {
			commit("updateAuthorizationPage", index);
		},
		changeAuthorization({
			state,
			commit
		}, index) {
			commit("updateAuthorization", index);
		},
		async connectDeviceInfo({
			state,
			commit
		}, uid) {
			console.log("刷新重连》》》》》》》》", state.$is_open_socket)
			if (state.deviceInfo.deviceId == "") {
				uni.showToast({
					title: "请扫码绑定设备",
					icon: "none",
					duration: 2000,
				});
				return
			}
			if (!state.$is_open_socket) {

				uni.showLoading({
					title: '服务器连接中'
				});

				const socket = await createSocket(uid);
				let heartbeatInterval; // 定义心跳包定时器

				// commit("addSocket",socket)
				socket.onOpen((res) => {
					console.log(state.userInfo.uid + "服务器连接中。。。。");
					commit('changeis_open_socket');
					// if(state.$is_open_socket){
					// 启动心跳包定时器
					clearInterval(heartbeatInterval);
					heartbeatInterval = setInterval(() => {
						socket.send(JSON.stringify({
							type: "heartbeat"
						}));
					}, 30000); // 每 30 秒发送一次心跳包

					socket.onMessage(async (res) => {

						if (res.data === "连接成功") {
							uni.hideLoading();
							if (state.deviceInfo.deviceId == "") {
								uni.showToast({
									title: "请扫码绑定设备",
									icon: "none",
									duration: 2000,
								});
							} else {
								uni.showToast({
									title: "服务器连接成功!",
									icon: "none",
									duration: 2000,
								});
							}


							console.log("连接成功")
							return
						}

						let data = {}
						try {
							data = res.data;
							let flag = false;
							console.log("收到新消息", JSON.parse(data))
							commit('setDeviceInfo', JSON.parse(data).status);


						} catch (e) {
							//TODO handle the exception

						}
					})
					// }

				})
				uni.stopPullDownRefresh();
				socket.onClose(() => {
					clearInterval(heartbeatInterval); // 清除心跳包定时器
					// commit('changeis_open_socket');
					uni.hideLoading();
					// commit('setDeviceInfo',3)
					commit('changeis_open_socket');
					uni.showToast({
						title: "服务器连接已关闭!",
						icon: "none",
						duration: 2000,
					});
					console.log("服务器连接已经被关闭")
				})
				socket.onError((e) => {
					clearInterval(heartbeatInterval); // 清除心跳包定时器
					uni.hideLoading();
					uni.showToast({
						title: "服务器连接失败!",
						icon: "none",
						duration: 2000,
					});
					console.log("设备连接失败")
					commit('changeis_open_socket');
					console.log(e)
				})
				// commit("addSocket",socket)
			}
		}
	},
	getters: {
		isAuthorizationPage: state => state.isAuthorizationPage,
		isAuthorization: state => state.isAuthorization,
		token: state => state.token,
		isLogin: state => !!state.token,
		userInfo: state => state.userInfo || {},
		location: state => state.location,
		storeItems: state => state.storeItems,
		goName: state => state.goName,
		$deviceType: state => state.$deviceType,
		deviceInfo: state => state.deviceInfo,
		deviceConect: state => state.deviceConect,
		deviceStauts: state => state.deviceStauts,
		$is_open_socket: state => state.$is_open_socket,
		windowWidth: state => state.windowWidth,
		statusBarHeight: state => state.statusBarHeight,
	},
	strict: debug
});

export default vuexStore